package com.wanpinghui.supplier.oauth;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.netease.nimlib.sdk.msg.MsgService;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.message.nim.NimManager;
import com.wanpinghui.supplier.object.HomePageActivity;
import com.wanpinghui.supplier.user.BusinessScopeActivity;
import com.wanpinghui.supplier.widgets.CodeCountDownTextView;
import com.wanpinghui.supplier.widgets.TitlePanelLayout;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.dialog.BaseDialogManager;
import com.wanpinghui.wphlibrary.common.dialog.YunBaseDialog;
import com.wanpinghui.wphlibrary.model.message.MessageService;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.oauth.bean.LoginResponseBean;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.widgets.ThrottleButton;
import com.yunshl.yunshllibrary.manager.MActivityManager;
import com.yunshl.yunshllibrary.utils.DevicesUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;
import com.yunshl.yunshllibrary.view.YunShlEditText;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.io.InputStream;

import retrofit.callback.YRequestCallback;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/11/21
 ***/
@ContentView(R.layout.layout_activity_login)
public class LoginActivity extends BaseActivity implements View.OnClickListener {
//    @ViewInject(R.id.tpl_title)
//    private TitlePanelLayout mLayoutTitle;
    @ViewInject(R.id.edt_phone)
    private YunShlEditText mEditTextPhone;
    @ViewInject(R.id.edt_code)
    private YunShlEditText mEditTextCode;
    @ViewInject(R.id.tv_agreement)
    private TextView mTextViewAgreement;
    @ViewInject(R.id.btn_submit)
    private ThrottleButton mButtonSubmit;
    @ViewInject(R.id.tv_get_code)
    private CodeCountDownTextView mTextViewGetCode;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {

    }

    @Override
    public void bindEvents() {
        mButtonSubmit.setOnThrottleClickListener(this);
        mTextViewGetCode.setOnClickListener(this);
        mTextViewAgreement.setOnClickListener(this);
//        mLayoutTitle.setOnClickBacktrack(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                MActivityManager.getInstance().delAllActivity();
//                finish();
//            }
//        });

        mButtonSubmit.addBindEdittext(mEditTextPhone, mEditTextCode);
        mEditTextPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtil.isNotEmpty(s.toString())) {
                    mTextViewGetCode.setEnabled(true);
                } else {
                    mTextViewGetCode.setEnabled(false);
                }
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                if (checkParams(true)) {
                    login();
                }
                break;
            case R.id.tv_get_code:
                if (checkParams(false)) {
                    sendCaptcha();
                }
                break;
            case R.id.tv_agreement:
                showAgreementView();
                break;
        }
    }

    private void showAgreementView() {
        View view = View.inflate(LoginActivity.this, R.layout.view_user_agreement, null);
        ScrollView scrollView = (ScrollView) view.findViewById(R.id.scrollView);
        scrollView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (DevicesUtil.getHeight(this) * 0.7)));
        TextView textView = (TextView) view.findViewById(R.id.tv_content);
        InputStream is = null;
        try {
            is = getAssets().open("agreement.txt");
            int size = is.available();
            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            // Convert the buffer into a string.
            String text = new String(buffer);
            textView.setText(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ImageView imageView = (ImageView) view.findViewById(R.id.iv_close);
        final YunBaseDialog dialog = BaseDialogManager.getInstance().getBuilder(LoginActivity.this).setContentView(view).create();
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        dialog.show();
    }

    private void login() {
        WPHSdk.getService(OAuthService.class)
                .login(mEditTextPhone.getTextString(), mEditTextCode.getTextString(),
                        new YRequestCallback<LoginResponseBean>() {
                            @Override
                            public void onSuccess(LoginResponseBean var1) {
                                cleanMsgCacheData();
                                getUserInformation();
                            }

                            @Override
                            public void onFailed(int var1, String message) {
                                showWarningText(message);
                            }

                            @Override
                            public void onException(Throwable var1) {
                                var1.printStackTrace();
                            }
                        });
    }

    private void cleanMsgCacheData(){
        //WPHSdk.getService(MessageService.class).cleanCacheData();
    }
    private void getUserInformation() {
        UserBean mUserBean = WPHSdk.getService(OAuthService.class)
                .getUserInfo(new YRequestCallback<UserBean>() {
                    @Override
                    public void onSuccess(UserBean var1) {
                        NimManager.getInstance().login();
                        if (var1.isWholeInfo()) {
                            if (var1.haveSerBusiness()) {
                                MActivityManager.getInstance().delACT(HomePageActivity.class);
                                startActivity(new Intent(LoginActivity.this, HomePageActivity.class));
                                finish();
                            } else {
                                Intent intent = new Intent(LoginActivity.this, BusinessScopeActivity.class);
                                intent.putExtra("from_login", true);
                                startActivity(intent);
                            }
                        } else {
                            Intent intent = new Intent(LoginActivity.this, InputInfoActivity.class);
                            intent.putExtra("from_login", true);
                            startActivity(intent);
                            //startActivity(new Intent(LoginActivity.this, InputInfoActivity.class));
                        }
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        showWarningText("登录失败，获取用户信息失败");
                    }

                    @Override
                    public void onException(Throwable var1) {
                        var1.printStackTrace();
                    }
                });

        if (mUserBean != null)
            NimManager.getInstance().login();
    }


    private void sendCaptcha() {
        WPHSdk.getService(OAuthService.class)
                .sendLoginCode(mEditTextPhone.getTextString(), new YRequestCallback() {
                    @Override
                    public void onSuccess(Object var1) {
                        mTextViewGetCode.startCountDown();
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        showWarningText(message);
                    }

                    @Override
                    public void onException(Throwable var1) {
                        var1.printStackTrace();
                    }
                });
    }

    private boolean checkParams(boolean filterCode) {
        if (TextUtil.isEmpty(mEditTextPhone.getTextString())) {
            showWarningText("请输入手机号");
            return false;
        } /*else if (!TextUtil.isPhoneNumber(mEditTextPhone.getTextString())) {
            showWarningText("请输入正确的手机号");
            return false;
        }*/
        if (filterCode) {
            if (TextUtil.isEmpty(mEditTextCode.getTextString())) {
                showWarningText("请输入验证码");
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            startActivity(new Intent(LoginActivity.this, HomePageActivity.class));
            finish();
        }
    }
}
